import { Text } from '@tarojs/components';
import Taro, { useLoad, useRouter } from '@tarojs/taro';
import { useState, useEffect } from "react";
import {AgentConfigure, ChatEmulator, SplForm} from "@/components";
import { useAgentSelector, useDispatchAgent } from "@/hooks/agent";
import { useConservationSelector, useDispatchConservation } from "@/hooks/conservation";
import { Tabs, Cell } from "@taroify/core";
import './index.css';
import '../agentConservation/index.css'

export default function AgentWorkspace() {
  const router = useRouter();
  const agent_uuid = router.params.uuid;
  const dispatchAgent = useDispatchAgent();
  const agentDetail = useAgentSelector(state => state.agent.agentDetail);
  const dispatchConservation = useDispatchConservation();
  const conservationDetail = useConservationSelector(state => state.conservation.conservationDetail);

  // 加载数据
  useLoad(() => {
    if (agent_uuid) {
      dispatchAgent.getAgentDetail(agent_uuid);
      console.log('Page loaded.');
    }
  });


  useEffect(() => {
    if (agentDetail) {
      const conservation_uuid = agentDetail.conservations[0].uuid;
      dispatchConservation.getConservationDetail(conservation_uuid);
      Taro.setNavigationBarTitle({
        title: agentDetail.name
      })
    }
  }, [agentDetail]);

  const handleSplChange = (newData) => {
    // 在这里处理 SPL 表单的更改
    console.log('SPL Form Changed:', newData);
  };

  const handleSendMessage = (message) => {
    // 处理发送消息的逻辑
    console.log('Sending message:', message);
  };

  const [value, setValue] = useState(1);

  return (
    <Tabs value={value} onChange={setValue} sticky>
      <Tabs.TabPane title='配置'>
        <Cell style={{height: 'calc(100vh - 100px)', overflow: 'auto'}}>
          {agentDetail ? (
            <AgentConfigure  agent={agentDetail} />
          ) : (
            <Text>加载中...</Text>
          )}
        </Cell>
      </Tabs.TabPane>
      <Tabs.TabPane title='设定'>
        <Cell style={{height: 'calc(100vh - 100px)', overflow: 'auto'}}>
          {agentDetail ? (
            <SplForm spl_form={agentDetail.spl_form} onChange={handleSplChange} />
          ) : (
            <Text>加载中...</Text>
          )}
        </Cell>
      </Tabs.TabPane>
      <Tabs.TabPane title='测试'>
        <Cell style={{height: 'calc(100vh - 100px)', overflow: 'auto'}}>
          {conservationDetail ? (
            <ChatEmulator conservation={conservationDetail} onSend={handleSendMessage} />
          ) : (
            <Text>加载中...</Text>
          )}
        </Cell>
      </Tabs.TabPane>
    </Tabs>
  );
}
